<?php
namespace  App\Http\Controllers\Radius;
use App\Extension_keyword;
use  App\Http\Controllers\Controller;


use Illuminate\Http\Request;

use App\Common\ErrorDefine;

use DB;

use App\Extension_platform;
use App\Extension_plan;
use App\Rad_manage;
use App\Extension;




class  TuiGuangController extends Controller
{
    private  $params = [];
    private  $page_size = 50;
    private  $page_no = 0;


    public function doPlatformAdd(Request $request)
    {
        if(!$request->has('platform_name') || empty($request->input('platform_name'))  )
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }
        $this->params['platform_name'] = $request->input('platform_name');

        $platform = Extension_platform::where($this->params)->first();

        if($platform != NULL)
        {
            self::ShowError(ErrorDefine::PLATFORM_EXTST);
            return;
        }
        $ret = Extension_platform::insert($this->params);

        return self::ShowMessage();
    }
    
    
    /**
     * @param Request $request
     * 获取平台列表数据
     */
    public function getPlatFormListData(Request $request)
    {

        //   开户人的 token
        if(!$request->has('token') && !empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');
        //   get manage userId
        $user = self::getTokenById($token);
        if(empty($user))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }

        $data = [];
        $platform = [];
        $plan_data = [];

        $platform = Extension_platform::all();
        $plan_data = Extension_plan::leftJoin('extension_platform','extension_plan.platform_id','=','extension_platform.id')
                        ->get(['extension_platform.platform_name','extension_plan.id','extension_plan.platform_id','extension_plan.plan_name','extension_plan.created_at']);
        $data['plan_data'] = $plan_data;
        $data['platform'] = $platform;

        return response()->json($data);


    }

    /**
     * @param Request $request
     * 修改平台信息
     */
    public function doPlatFormModify(Request $request)
    {
        if(!$request->has('platform_id') || empty($request->input('platform_id'))  )
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }
        $id = $request->input('platform_id');

        if(!$request->has('platform_name') || empty($request->input('platform_name'))  )
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }
        $name = $request->input('platform_name');

        $platform = Extension_platform::find($id);

        if($platform == NULL)
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }

        $platform->platform_name = $name;
        $platform->save();

        return self::ShowMessage();

    }

    /**
     * @param Request $request
     * 删除平台信息
     */
    public function doPlatFormDelete(Request $request)
    {
        if(!$request->has('platform_id') || empty($request->input('platform_id'))  )
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }
        $id = $request->input('platform_id');

        $platform = Extension_platform::find($id);

        if($platform == NULL)
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }


        $plan = Extension_plan::where('platform_id',$id)->first();

        if($plan != NULL)
        {
            self::ShowError(ErrorDefine::PLATFORM_EXIST_PLAN);
            return;
        }

        $platform->delete();

        return self::ShowMessage();

    }





    /**
     *  添加平台推广计划
     */
    public function addExtensionPlan(Request $request)
    {
        if(!$request->has('platform_id') || empty($request->input('platform_id'))  )
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }
        $this->params['platform_id'] = $request->input('platform_id');

        if(!$request->has('plan_name') || empty($request->input('plan_name'))  )
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }
        $this->params['plan_name'] = $request->input('plan_name');


        $plan = Extension_plan::where($this->params)->first();
        if($plan != NULL){
            self::ShowError(ErrorDefine::PLAN_EXIST);
            return;
        }


        $id = Extension_plan::insertGetId($this->params);

        return self::ShowMessage();



    }

    /**
     *  修改平台推广计划
     */
    public function doExtensionPlanModify(Request $request)
    {
        if(!$request->has('platform_id') || empty($request->input('platform_id'))  )
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }
        $this->params['platform_id'] = $request->input('platform_id');


        if(!$request->has('plan_name') || empty($request->input('plan_name'))  )
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }
        $this->params['plan_name'] = $request->input('plan_name');


        $plan = Extension_plan::where($this->params)->first();


        if($plan != NULL){
            self::ShowError(ErrorDefine::PLAN_NAME_EXIST);
            return;
        }

        if(!$request->has('plan_id') || empty($request->input('plan_id'))  )
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }

        $this->params['id'] = $request->input('plan_id');

        $plan2 = Extension_plan::find($this->params['id']);

        if($plan2 == NULL){
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }

        $plan2->plan_name = $this->params['plan_name'];
        $plan2->save();

        return self::ShowMessage();


    }

    /**
     *  删除平台推广计划
     */
    public function doExtensionPlanDelete(Request $request)
    {
        if(!$request->has('plan_id') || empty($request->input('plan_id')) )
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }

        $this->params['id'] = $request->input('plan_id');


        $plan = Extension_plan::find($this->params['id']);


        if($plan == NULL)
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }

        $keyword =  Extension_keyword::where('plan_id',$this->params['id'])->first();
        if($keyword != NULL){
            self::ShowError(ErrorDefine::PLAN_EXIST_KEYWORD);
            return;
        }


        $plan->delete();

        return self::ShowMessage();


    }


    /**
     * @param Request $request
     *  获取平台下推广计划
     */
    public function getPlanListData(Request $request)
    {
        if(!$request->has('platform_id') || empty($request->input('platform_id')) )
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }

        $this->params['platform_id'] = $request->input('platform_id');

        $plans = Extension_plan::where('platform_id', $this->params['platform_id'])->get(['id','plan_name']);

        return self::ShowMessage($plans);


    }

    /**
     * @param Request $request
     *  添加平台下推广计划关键词
     */
    public function doKeyWordAdd(Request $request)
    {
        if(!$request->has('platform_id') || empty($request->input('platform_id')) )
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }

        $this->params['platform_id'] = $request->input('platform_id');

        if(!$request->has('plan_id') || empty($request->input('plan_id')) )
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }

        $this->params['plan_id'] = $request->input('plan_id');


        if(!$request->has('keyword') || empty($request->input('keyword')) )
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }
        $keyword= $request->input('keyword');


        foreach ($keyword as $value)
        {
            $this->params['keyword_name'] = $value['keyword'];
            $this->params['pc_keyword_url'] = $value['pcurl'];
            $this->params['wap_keyword_url'] = $value['wapurl'];

            try{
                Extension_keyword::insert($this->params);
            }catch (\Exception $e){
                self::ShowError(ErrorDefine::INVALID_PARAMS);
                return;
            }

        }

            return self::ShowMessage();


    }


    /**
     * @param Request $request
     * 获取推广计划关键词数据
     */
    public function getKeyWordListData(Request $request)
    {

        $keyword = new Extension_keyword();

        if($request->has('platform_id') && !empty($request->input('platform_id')) )
        {
            $keyword =  $keyword->where('extension_keyword.platform_id',$request->input('platform_id'));
        }

        if($request->has('plan_id') && !empty($request->input('plan_id')) )
        {
            $keyword =  $keyword->where('extension_keyword.plan_id',$request->input('plan_id'));
        }



        if($request->input('page_no'))
        {
            $this->page_no  = $request->input('page_no');
            if($this->page_no){
                $this->page_no = $this->page_no - 1;
                if(is_numeric($this->page_no)){
                    if($this->page_no<0){
                        $this->page_no = 0;
                    }
                }
            }
        }

        if($request->input('page_size'))
        {
            $this->page_size = $request->input('page_size');
            if($this->page_size){
                if($this->page_size <=0 ){
                    $this->page_size =  50;
                }
            }
        }
        $count = $keyword->count();

        $data = $keyword->leftJoin('extension_plan','extension_keyword.plan_id','=','extension_plan.id')
                ->leftJoin('extension_platform','extension_keyword.platform_id','=','extension_platform.id')
                ->offset($this->page_no*$this->page_size)->limit($this->page_size)
                ->get(['extension_plan.plan_name','extension_platform.platform_name',
                    'extension_keyword.keyword_name','extension_keyword.pc_keyword_url',
                    'extension_keyword.wap_keyword_url','extension_keyword.created_at']);

        return self::ShowData($data,$count);


    }


    /**
     * @param Request $request
     *  修改平台推广关键字列表数据
     */
    public function doKeyWordUpdate(Request $request)
    {
        if(!$request->has('platform_id') || empty($request->input('platform_id')) )
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }

        $this->params['platform_id'] = $request->input('platform_id');


        if(!$request->has('plan_id') || empty($request->input('plan_id')) )
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }
        $this->params['plan_id'] = $request->input('plan_id');

        if(!$request->has('keyword') || empty($request->input('keyword')) )
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }
        $keyword= $request->input('keyword');

        if(!empty($keyword)){
            foreach ($keyword as $value){
                $this->params['keyword_name'] = $value['keyword'];
                $ret = Extension_keyword::where($this->params)->first();
                if($ret != NULL )
                {
                    Extension::where('keyword_name',$ret->keyword_name)->where('terminal_id',2)->where('plan_id',$this->params['plan_id'])->update(['extension_url'=>$value['pcurl']]);
                    Extension::where('keyword_name',$ret->keyword_name)->where('terminal_id',1)->where('plan_id',$this->params['plan_id'])->update(['extension_url'=>$value['wapurl']]);
                    $ret->pc_keyword_url = $value['pcurl'];
                    $ret->wap_keyword_url = $value['wapurl'];
                    $ret->save();
                }

            }
        }

        return self::ShowMessage();



    }

    /**
     * @param Request $request
     * 统计添加
     */
    public function addStatictis(Request $request)
    {

        $url = $request->input('url');
        // 终端ID
        $this->params['terminal_id'] = $request->input('terminal_id');
        // IP
        $this->params['ip'] = $request->input('ip');


        if(!array_key_exists('query', parse_url($url)))
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }
        $key = parse_url($url)['query'];

        $extension_url = 'http://www.niumoip.com/?'.$key;


        switch ($this->params['terminal_id']){
            case 1:$extension_info = Extension_keyword::where('wap_keyword_url',$extension_url)->first(); break;//  wap 端
            case 2:$extension_info = Extension_keyword::where('pc_keyword_url',$extension_url)->first();break;//  pc  端
        }

        if($extension_info == NULL)
        {
            return ;
        }

        $this->params['platform_id'] = $extension_info->platform_id;    //  平台ID
        $this->params['plan_id'] = $extension_info->plan_id;            //  计划ID
        $this->params['keyword_name'] = $extension_info->keyword_name;  //  关键词
        $this->params['extension_url'] = $extension_url;                //  推广URL
        $this->params['code'] = $request->input('code');                //  推广URL

        $extension = Extension::where($this->params)->first();

        if($extension != NULL)
        {
            switch ($request->input('action')){
                case 'click':$extension->click = $extension->click + 1;$extension->status = $request->input('status');break;                        //点击
                case 'consultation':$extension->consultation = $extension->consultation + 1;$extension->status = $request->input('status');break;   // 咨询
                case 'download':$extension->download = $extension->download + 1;$extension->status = $request->input('status');break;               // 下载
                case 'register':$extension->register = $extension->register + 1;$extension->status = $request->input('status');break;               // 注册
                case 'buy':$extension->buy = $extension->buy + 1;
                            $extension->order_no = $request->input('order_no');
                            $extension->money = $request->input('money');
                            $extension->status = $request->input('status');
                            break;                              // 注册
            }
            $extension->save();


        }else{

            $ret = Extension::insertGetId($this->params);
        }







    }


    /**
     * @param Request $request
     * 推广数据
     */
    public function getExtensionData(Request $request)
    {

        $extension = new Extension();

        if($request->has('platform_id') && !empty($request->input('platform_id')))
        {
            $extension =  $extension->where('extension.platform_id',$request->input('platform_id'));
        }

        if($request->has('plan_id') && !empty($request->input('plan_id')) )
        {
            $extension =  $extension->where('extension.plan_id',$request->input('plan_id'));
        }

        if($request->has('start_date') && !empty($request->input('start_date')))
        {
            $extension =  $extension->where('extension.created_at','>',$request->input('start_date'));
        }else{
            $extension =  $extension->where('extension.created_at','>',date('Y-m-d',time()));

        }

        if($request->has('end_date') && !empty($request->input('end_date')))
        {
            $extension =  $extension->where('extension.created_at','<',$request->input('end_date'));
        }else{
            $extension =  $extension->where('extension.created_at','<',date('Y-m-d H:i:s',time()));
        }

        if($request->has('field') && $request->has('order'))
        {
            $extension =  $extension->orderBy('extension.'.$request->input('field'),$request->has('order'));
        }


        $arr = [];

        $count = $extension->count();
        $arr['click_num'] = $extension->distinct('ip')->sum('click');
        $arr['consultation_num'] = $extension->distinct('ip')->sum('consultation');
        $arr['download_num'] = $extension->distinct('ip')->sum('download');
        $arr['register_num'] = $extension->distinct('ip')->sum('register');
        $arr['buy_num'] = $extension->distinct('ip')->sum('buy');


        if($request->input('page_no'))
        {
            $this->page_no  = $request->input('page_no');
            if($this->page_no){
                $this->page_no = $this->page_no - 1;
                if(is_numeric($this->page_no)){
                    if($this->page_no<0){
                        $this->page_no = 0;
                    }
                }
            }
        }

        if($request->input('page_size'))
        {
            $this->page_size = $request->input('page_size');
            if($this->page_size){
                if($this->page_size <=0 ){
                    $this->page_size =  50;
                }
            }
        }


        $data = $extension->leftJoin('extension_platform','extension.platform_id','=','extension_platform.id')
                ->leftJoin('extension_plan','extension.plan_id','=','extension_plan.id')
                ->leftJoin('extension_terminal_type','extension.terminal_id','=','extension_terminal_type.id')
                ->offset($this->page_no*$this->page_size)->limit($this->page_size)
                ->get(['extension.platform_id','extension_platform.platform_name','extension.plan_id','extension_plan.plan_name',
                'extension_terminal_type.terminal_name','extension.extension_url','extension.keyword_name','extension.ip',
                'extension.order_no','extension.money','extension.created_at','extension.click','extension.download',
                    'extension.register','extension.consultation','extension.buy']);

        return self::ShowData($data,$count,$arr);

















    }


    /**
     * @param Request $request
     * 推广数据下载
     */
    public function downloadExtensionData(Request $request)
    {
        $extension = new Extension();

        if($request->has('platform_id') && !empty($request->input('platform_id')))
        {
            $extension =  $extension->where('extension.platform_id',$request->input('platform_id'));
        }

        if($request->has('plan_id') && !empty($request->input('plan_id')) )
        {
            $extension =  $extension->where('extension.plan_id',$request->input('plan_id'));
        }

        if($request->has('start_date') && !empty($request->input('start_date')))
        {
            $extension =  $extension->where('extension.created_at','>',$request->input('start_date'));
        }

        if($request->has('end_date') && !empty($request->input('end_date')))
        {
            $extension =  $extension->where('extension.created_at','<',$request->input('end_date'));
        }

        if($request->has('field') && $request->has('order'))
        {
            $extension =  $extension->orderBy('extension.'.$request->input('field'),$request->has('order'));
        }


        $data = $extension->leftJoin('extension_platform','extension.platform_id','=','extension_platform.id')
            ->leftJoin('extension_plan','extension.plan_id','=','extension_plan.id')
            ->leftJoin('extension_terminal_type','extension.terminal_id','=','extension_terminal_type.id')

            ->get(['extension.platform_id','extension_platform.platform_name','extension.plan_id','extension_plan.plan_name',
                'extension_terminal_type.terminal_name','extension.extension_url','extension.keyword_name','extension.ip',
                'extension.order_no','extension.money','extension.created_at','extension.click','extension.download',
                'extension.register','extension.consultation','extension.buy']);

        return self::ShowMessage($data);
    }
    


    static function getTokenById($token)
    {
        $user = Rad_manage::where('token',$token)->get()->toArray();
        return $user;
    }


}